/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package logging;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.naming.NamingException;
import javax.sql.DataSource;
import ru.ssau.utils.DatabaseUtil;


public class EntityLoggerBean implements MessageDrivenBean, MessageListener {

    public static final String ENTITY_ID = "entityId";
    public static final String CHANGE_TIME = "changeTime";
    public static final String ENTITY_NAME = "entityName";
    public static final String PERFORMED_ACTION = "performedAction";

    /*private static final String REQUEST_LOG_ADD_RECORD =
            "INSERT INTO LogRecord(id, entityId, entityName, changeTime) VALUES(?, ?, ?, ?)";
    private static final String REQUEST_LOG_ID_SEQUENCE_GET_NEXT_VALUE =
            "SELECT LogRecordIDSeq.NEXTVAL FROM dual";*/

    private MessageDrivenContext mdContext;
    private DataSource dataSource;

    public EntityLoggerBean() {
        
    }

    public void ejbCreate() {
        try {
            dataSource = DatabaseUtil.getDataSource();
        } catch(NamingException ex) {
            System.out.println("Cannot find DataSource object");
            ex.printStackTrace();
        }
    }

    public void ejbRemove() {

    }

    public void setMessageDrivenContext(MessageDrivenContext context) {
        mdContext = context;
    }

    public void onMessage(Message message) {
        if(!(message instanceof MapMessage)) {
            System.out.println("Unsupported message type. MapMessage required");
            return;
        }
        MapMessage mapMessage = (MapMessage) message;

        Connection conn = null;
        PreparedStatement idGeneratePS = null;
        PreparedStatement updatePS = null;
        try {
            conn = dataSource.getConnection();
            idGeneratePS = conn.prepareStatement("SELECT LogRecordIDSeq.NEXTVAL FROM dual");
            ResultSet rs = idGeneratePS.executeQuery();
            if(!rs.next()) {
                System.out.println("Cannot generate ID for Log Record");
            }
            int id = rs.getInt(1);
            int entityId = mapMessage.getInt(ENTITY_ID);
            String entityName = mapMessage.getString(ENTITY_NAME);
            Timestamp changeTime = new Timestamp(mapMessage.getLong(CHANGE_TIME));
            String action = mapMessage.getString(PERFORMED_ACTION);
            updatePS = conn.prepareStatement("INSERT INTO LogRecord(id, entityId, entityName, changeTime, performedAction) VALUES(?, ?, ?, ?, ?)");
            updatePS.setInt(1, id);
            updatePS.setInt(2, entityId);
            updatePS.setString(3, entityName);
            updatePS.setTimestamp(4, changeTime);
            updatePS.setString(5, action);
            updatePS.executeUpdate();
        } catch(SQLException ex) {
            System.out.println("Database access error");
            ex.printStackTrace();
        } catch(JMSException ex) {
            System.out.println("Error in received message");
            ex.printStackTrace();
        }
        finally {
            DatabaseUtil.closeConnection(conn, idGeneratePS);
            DatabaseUtil.closeConnection(null, updatePS);
        }
    }

}
